<template>
  <div>
    <el-date-picker
      style="width: 250px"
      :clearable="clearable"
      size="small"
      @change="handlerChange"
      :shortcuts="shortcuts"
      value-format="X"
      class="el-date-picker"
      v-model="timeList"
      :type="type"
      range-separator="至"
      start-placeholder="开始时间"
      end-placeholder="结束时间"
    />
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import TimeUtil from "@/utils/time-util.js";

const props = defineProps({
  clearable: {
    type: Boolean,
    default: false,
  },
  type:{
    type: String,
    default: "daterange"
  },
  timeValue:{
    type: Array,
    default: () => ([])
  },
})
const shortcuts= ref([
  {
    text: "最近一周",
    value:() =>{
      const now = new Date();
      const year = now.getFullYear();
      const month =
        now.getMonth() + 1 > 10
          ? now.getMonth() + 1
          : "0" + (now.getMonth() + 1);
      const day =
        now.getDate() > 10 ? now.getDate() : "0" + now.getDate();
      const end = `${year}/${month}/${day} 23:59:59`;
      const start =
        day - 7 > 0
          ? `${year}/${month}/${day - 7} 00:00:00`
          : new Date(end).getTime() - 1000 * 3600 * 24 * 7 + 1000;
      return [start, end]
    },
  },
  {
    text: "最近一个月",
    value:() =>{
      const now = new Date();
      const year = now.getFullYear();
      const month =
        now.getMonth() + 1 > 10
          ? now.getMonth() + 1
          : "0" + (now.getMonth() + 1);
      const day =
        now.getDate() > 10 ? now.getDate() : "0" + now.getDate();
      const start =
        month - 1 > 0
          ? `${year}/${month - 1}/${day} 00:00:00`
          : `${year - 1}/${12}/${day} 00:00:00`;
      const end = `${year}/${month}/${day} 23:59:59`;
      return [start, end]
    },
  },
  {
    text: "最近三个月",
    value:() =>{
      const now = new Date();
      const year = now.getFullYear();
      const month =
        now.getMonth() + 1 > 10
          ? now.getMonth() + 1
          : "0" + (now.getMonth() + 1);
      const day =
        now.getDate() > 10 ? now.getDate() : "0" + now.getDate();
      const start =
        month - 3 > 0
          ? `${year}/${month - 3}/${day} 00:00:00`
          : month - 3 == 0
            ? `${year - 1}/12/${day} 00:00:00`
            : month - 3 == -1
              ? `${year - 1}/11/${day} 00:00:00`
              : `${year - 1}/10/${day} 00:00:00`;
      const end = `${year}/${month}/${day} 23:59:59`;
      return [start, end]
    },
  },
])
const timeList = ref([])

watch(()=>props.timeValue, (newVal) => {
  timeList.value = newVal
}, {immediate: true})

const handlerChange = (e) => {
  if(timeList.value.length > 0) {
    timeList.value[0] = timeList.value[0] * 1
    timeList.value[1] = TimeUtil.getTimeStampToEnd(timeList.value[1] * 1000)
  }
  emit('handlerTimeChange', timeList.value)
}
const emit = defineEmits(['handlerTimeChange'])
</script>

<style scoped>

</style>
